import { useEffect, useState } from "react";
import {
  DragDropContext,
  Droppable,
  Draggable,
  DropResult,
  DroppableProvided,
  DroppableStateSnapshot,
  DraggableProvided,
  DraggableStateSnapshot,
} from "react-beautiful-dnd";

const crateData = (count: number) =>
  new Array(count).fill("item").map((item, index) => ({
    id: `${item}-${index}`,
    content: `内容xxxx${index}`,
  }));

const reorder = <T extends unknown>(
  list: T[],
  startIndex: number,
  endIndex: number
): T[] => {
  const newList = Array.from(list);
  const [remove] = newList.splice(startIndex, 1);
  newList.splice(endIndex, 0, remove);
  return newList;
};

export const TestReactBeautifulDnd = () => {
  const [itemList, setItemList] = useState(crateData(5));
  const onDragEnd = (res: DropResult) => {
    console.log("拖拽结束----", res);
    const { source, destination } = res;
    if (
      source.droppableId == destination?.droppableId &&
      source.index == destination.index
    )
      return;
    setItemList((list) => reorder(list, source.index, destination?.index || 0));
  };
  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Droppable droppableId="basic" type="basic">
        {(provided: DroppableProvided, snapshot: DroppableStateSnapshot) => (
          <div ref={provided.innerRef} {...provided.droppableProps}>
            {itemList.map((item, index) => (
              <Draggable draggableId={item.id} index={index} key={item.id}>
                {(
                  dragProvided: DraggableProvided,
                  snapshot1: DraggableStateSnapshot
                ) => (
                  <div
                    ref={dragProvided.innerRef}
                    {...dragProvided.draggableProps}
                    {...dragProvided.dragHandleProps}
                  >
                    {item.id}-{item.content}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};
